package hu.lacimol.tutorial.todo.service;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;

import hu.lacimol.tutorial.todo.model.Comment;
import hu.lacimol.tutorial.todo.model.Todo;

import java.util.List;

import net.java.ao.Query;

import com.atlassian.activeobjects.external.ActiveObjects;

public final class TodoServiceImpl implements TodoService {

	private final ActiveObjects ao;

	public TodoServiceImpl(ActiveObjects ao) {
		this.ao = checkNotNull(ao);
	}

	@Override
	public Todo create(String description) {
		final Todo todo = ao.create(Todo.class);
		todo.setDescription(description);
		todo.setComplete(false);
		todo.save();
		return todo;
	}

	@Override
	public List<Todo> findAll() {
		return newArrayList(ao.find(Todo.class));
	}

	@Override
	public List<Todo> find(String description) {
		return newArrayList(ao.find(Todo.class, Query.select().where("description = ?", description)));
	}

	@Override
	public void addComment(Todo todo, String text) {
		Comment comment = ao.create(Comment.class);
		comment.setTodo(todo);
		comment.setText(text);
		comment.save();
	}

	@Override
	public Todo findById(int id) {
		//return ao.find(Todo.class, Query.select().where("id = ?", id);
		return ao.get(Todo.class, id);
	}

	@Override
	public void delete(int id) {
		Todo todo = ao.get(Todo.class, id);
		ao.delete(todo.getComments());
		ao.delete(todo);
	}

}